package com.yanwq.sayhi.controller.audio;

import android.media.MediaPlayer;

import java.io.IOException;

/**
 * 作者：yanweiqiang。
 * 日期：2016/2/16 10:57。
 */
public class AudioPlayerWrap {

    public AudioPlayerWrap() {

    }

    public void play(String filePath, final MediaPlayer.OnCompletionListener listener) {
        final MediaPlayer mediaPlayer = new MediaPlayer();

        if (mediaPlayer.isPlaying()) {
            mediaPlayer.reset();
        }

        try {
            mediaPlayer.setDataSource(filePath);
            mediaPlayer.prepare();
            mediaPlayer.start();
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer arg0) {
                    listener.onCompletion(mediaPlayer);
                    mediaPlayer.release();
                }
            });
            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer player, int arg1, int arg2) {
                    listener.onCompletion(mediaPlayer);
                    mediaPlayer.release();
                    return false;
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
